import re
import yaml

from ActiveUser import ActiveUser

from msg import *
from SendToNeighbours import send_message_to_neighbors
import globals

def updateActiveUserList (mp, message) :

    if (message.mtype == 'check_in_nodes') :
        print "Checkin Message received from Src %s" % (message.src)

        activeUser = yaml.load(message.data)
        try :
            globals.globalActiveUserListLock.acquire()
            globals.globalActiveUserList[activeUser.userName] = activeUser
        finally :
            globals.globalActiveUserListLock.release()
        #globalActiveUserList.append(activeUser)
        # print globalActiveUserList

        #send this message to the neighbouring nodes
        #print "About to send message to nodes after receiving in updateActiveUserList"

        send_message_to_neighbors (mp, message)
        return

    elif (message.mtype == 'check_out_nodes') :

        #print "Checkout Message received from Src %s" % (message.src)
        #for item in globalActiveUserList :
        #    if item.userName == message.data :
        #        print "User checked out -> %s" % (item.userName)
        #        globalActiveUserList.remove(item)
        #        break
        try :
            globals.globalActiveUserListLock.acquire()
            if message.data in globals.globalActiveUserList :
                del globals.globalActiveUserList[message.data]
        finally :
            globals.globalActiveUserListLock.release()
            #print "Global active user list after checking out is : "
            #print globalActiveUserList
        #for item in globalActiveUserList :
        #    print item.userName
        #send this message to the neighbouring nodes
            message.src = mp.thisName
            send_message_to_neighbors (mp, message)
            return

    return
